const MYSQL = require("../../sql/mysql");
// MYSQL数据库配置信息
const MYSQLConfig = require("../../sql/database");
let sqlName = MYSQLConfig.datasheetName.roles;
/**
 * 角色列表
 * @param {object} params
 * @param {string} params.page 页码
 * @param {string} params.limit 每页数据条数
 * @param {object} params.where 查询条件
 * @returns {Promise<{code:string,msg:string,data:[object]}>}
 */
module.exports = async (params = {}) => {
  try {
    let { page = 1, limit = 10, where = {} } = params;
    let queryWhere = whereHandle(where);
    limit = limit < 1 ? (limit = 1) : limit;
    page = page < 1 ? (page = 1) : page;
    // 查询数据
    let query = `
      SELECT * FROM ${sqlName} ${queryWhere} 
      LIMIT ${(page - 1) * limit + "," + page * limit}
    `;
    // 获取列表数据
    let mysqlLIst = await MYSQL.promise().query(query);

    let list = mysqlLIst[0];

    // 获取数据总数 =====
    let totalResult = await MYSQL.promise().query(
      `
      SELECT Count(*) AS total FROM ${sqlName} ${queryWhere}
      `
    );
    let total = totalResult[0][0].total;

    let pages = Math.ceil(total / limit)
    return {
      code: 0,
      msg: "获取成功",
      newData: {
        pages,
        page,
        limit,
        total,
        data: list,
      },
      data: list,
    };
  } catch (error) {
    console.log(error);
    throw { code: 500, msg: "获取角色列表失败" };
  }
};
